package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.Result;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 样例过滤器
 *
 * @author liudo
 * @version 1.0
 * @project tlias-backend
 * @date 2023/9/12 14:21:46
 */
@Slf4j
// @WebFilter(urlPatterns = "/*") // 过滤所有请求
// @WebFilter(urlPatterns = "/emps/*") // 过滤以User开头的所有请求
public class LoginCheckFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info("---------------------------LoginCheckFilter-------------------------");

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        // 0.如果是登录接口，我们直接放行
        String requestURI = httpServletRequest.getRequestURI();
        if (requestURI.contains("/login")) {
            // 放行之前的所有代码处理
            chain.doFilter(request, response);
            // 后面就是对响应的拦截
            log.info("------------------------");
            return;
        }
        // 1. 获取令牌，看看有没有？ -- 令牌在哪？ 请求头
        String token = httpServletRequest.getHeader("Token");
        if (!StringUtils.hasText(token)) {
            // 不放行，但是要返回固定的结果 { "code": 0, "msg": "NOT_LOGIN", "data": null }
            Result<Object> result = new Result<>();
            result.setCode(0);
            result.setMsg("NOT_LOGIN");
            // 把对象转成json
            String jsonString = JSON.toJSONString(result);
            // 把json写进响应体
            httpServletResponse.getWriter().write(jsonString);
            return;
        }
        // 2. 看看令牌非法不非法
        try {
            Claims body = Jwts.parser()
                    .setSigningKey("itheima")
                    .parseClaimsJws(token)
                    .getBody();
            chain.doFilter(request, response);
        } catch (Exception e) {
            // 3. 如果不放行，我该如何通知前端进行登录呢? -- 不是随便报错 -- 接口文档
            Result<Object> result = new Result<>();
            result.setCode(0);
            result.setMsg("NOT_LOGIN");
            // TODO 手动给它变JSON 放进响应体中 这里需要序列化工具
            String jsonString = JSON.toJSONString(result);
            httpServletResponse.getWriter().write(jsonString);
        }
    }

}
